package com.xneure.database.metaobject;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.xneure.database.annotation.DBTable;
import com.xneure.utils.ObjectUtil;
import com.xneure.utils.bean.BeanProcessor;
import com.xneure.utils.bean.ClassProperty;

public class TableMetaObject extends MetaObject{
	private String tableName;
	private Map<String,FieldMetaObject> fields;
	private FieldMetaObject idKey;

	public TableMetaObject(Class<?> cls){
		super(cls);
		loadField();
	}

	public String getTableName(){
		if(null == tableName){
			return tableName = getTableName(getType());
		}
		return tableName;
	}

	public Map<String,FieldMetaObject> getFields(){
		if(null == fields){
			loadField();
		}
		return new LinkedHashMap<>(fields);
	}

	public DBTable getAnnotation(){
		return (DBTable)super.getAnnotation();
	}

	protected void loadField(){
		Class<?> cls = getType();
		Map<String,ClassProperty> _fields = BeanProcessor.getBeanInfo(cls);
		this.fields = new LinkedHashMap<>(20);
		for(Entry<String,ClassProperty> ent:_fields.entrySet()){
			FieldMetaObject e = new FieldMetaObject(this,ent.getValue());
			if(e.isIdKey()){
				idKey = e;
			}
			if(null != e.getAnnotation() && e.getAnnotation().value().length() > 0 && !e.isIgnore()){
				this.fields.put(e.getAnnotation().value().toLowerCase(),e);
			}else{
				this.fields.put(ent.getKey().toLowerCase(),e);
			}
		}
	}

	public FieldMetaObject getIdKey(){
		return idKey;
	}

	protected String getTableName(Class<?> cls){
		String value = cls.getSimpleName();
		DBTable ant = cls.getAnnotation(DBTable.class);
		if(ObjectUtil.isNotNull(ant)){
			if(ant.value().length() > 0){
				value = ant.value();
			}
			if(ant.space().length() > 0){
				value = ant.space().concat(".").concat(value);
			}
			setAnnotation(ant);
		}else{
			if(ObjectUtil.isBasicType(cls)){
				throw new RuntimeException("不支持的实体类型：".concat(value));
			}
		}
		return value;
	}
}
